<?php namespace App\Http\Controllers\user\industry;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Illuminate\Pagination\LengthAwarePaginator;
use Landish\Pagination\Pagination as BootstrapPresenter;

use App\Models\Projects;
use App\Models\Domains;
use App\Models\Techs;
use App\Models\Devices;
use App\Models\Technologies;
use App\Models\Collecttion;
use Input;
use App;
use DB;
use App\Models\ProjectBidding;
use Session;

class ProjectController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{

		// return DB::select(DB::raw('select * from tyw_projects where id in (select project_id from tyw_project_domain where cate_id=17 or cate_id in (select id from tyw_domains where parent_id=1)) and id in (select project_id from tyw_project_tech where cate_id=1)'));

		//->whereIn("id", DB::table("project_domain")->where("cate_id", 17)->orWhereIn("cate_id", DB::table("domains")->where("parent_id", 1)->lists("id"))->lists("project_id"))->whereIn("id", DB::table("project_tech")->where("cate_id", 12)->orWhereIn("cate_id", DB::table("techs")->where("id", 12)->lists("id"))->lists("project_id"))

		$numPerPage = 12;
		$projects = Projects::with(['province', 'city', 'area', "user", "projectDomain", "projectDomain.domain", "projectDomain.domain.parent", "projectTech", "projectTech.tech", "investmentType", "mainBody", "mainBody.mainBody", "technologies", "technologies.technology", "devices", "devices.device"])->where("verify_state", 1);

		if(Input::has("aid")){
			$projects->whereIn("id", DB::table("project_domain")->whereIn("cate_id", DB::table("domains")->where("parent_id", Input::get("aid"))->lists("id"))->lists("project_id"))->orWhereIn("id", DB::table("project_domain")->where("cate_id", Input::get("aid"))->lists("project_id"));
		}

		if(Input::has("cid"))
		{
			$projects->whereIn("id", DB::table("project_domain")->where("cate_id", Input::get("cid"))->lists("project_id"));
		}

		if(Input::has("tid"))
		{
			$projects->whereIn("id", DB::table("project_tech")->where("cate_id", Input::get("tid"))->lists("project_id"));
		}

		$count = $projects->count();
		$curPage = (int)Input::get("page", 1);
		$p = new LengthAwarePaginator($projects, $count, $numPerPage, $curPage);
		$p->setPath("");
        $presenter = new BootstrapPresenter($p);

		$domains = Domains::with(["children" => function($query){
			$query->where("parent_id", Input::get("aid", 1));
		}])->where("parent_id", 0)->get()->toArray();
		$techs = Techs::all();

		$projects = $projects->orderBy("id", "desc")->skip(($curPage - 1) * $numPerPage)->take($numPerPage)->get();

		foreach($projects as $p){
			switch($p["user"]["role_id"]){
				case env("ENERGY"):
					$p->load("user.poweruser");
					$p["userData"] = $p["user"]["poweruser"];
					unset($p["user"]["poweruser"]);
				break;
				case env("SAVER"):
					$p->load("user.energysaver");
					$p["userData"] = $p["user"]["energysaver"];
					unset($p["user"]["energysaver"]);
				break;
				case env("DEVICE_TECH"):
					$p->load("user.devicetech");
					$p["userData"] = $p["user"]["devicetech"];
					unset($p["user"]["devicetech"]);
				break;
				case env("THIRD"):
					$p->load("user.thirdparty");
					$p["userData"] = $p["user"]["thirdparty"];
					unset($p["user"]["thirdparty"]);
				break;
				case env("ASSOCIATION"):
					$p->load("user.association");
					$p["userData"] = $p["user"]["association"];
					unset($p["user"]["association"]);
				break;
				case env("GOVERNMENT"):
					$p->load("user.government");
					$p["userData"] = $p["user"]["government"];
					unset($p["user"]["government"]);
				break;
			}
		}

		$projects = $projects->toArray();

		$recProject = Projects::with(["projectDomain", "projectDomain.domain", "projectDomain.domain.parent", "projectTech", "projectTech.tech", "investmentType", "mainBody", "mainBody.mainBody", "technologies", "technologies.technology", "devices", "devices.device"])->where("verify_state", 1)->where("is_rec", 1)->orderBy("order", "desc")->skip(($curPage - 1) * 5)->take(5)->get()->toArray();

		$bottomNumPerPage = 6;
		$bottomProject = Projects::with(["projectDomain", "projectDomain.domain", "projectDomain.domain.parent", "projectTech", "projectTech.tech", "investmentType", "mainBody", "mainBody.mainBody", "technologies", "technologies.technology", "devices", "devices.device"])->where("verify_state", 1)->where("is_rec_list_bottom", 1)->skip(($curPage - 1) * $bottomNumPerPage)->take(6)->get()->toArray();
		$bottomDevice = Devices::where("is_rec_list_bottom", 1)->where("verify_state", 1)->skip(($curPage - 1) * $bottomNumPerPage)->take(6)->get()->toArray();
		$bottomTech = Technologies::where("is_rec_list_bottom", 1)->where("verify_state", 1)->skip(($curPage - 1) * $bottomNumPerPage)->take(6)->get()->toArray();

		$queryStr = "";
		foreach (Input::all() as $key => $value)
		{
			$queryStr .= $key . "=" . $value . "&";
		}
		$params = ["projects" => $projects, "count" => $count, "domains" => $domains, "techs" => $techs, "recommand" => $recProject, "bottomProject" => $bottomProject, "bottomDevice" => $bottomDevice, "bottomTech" => $bottomTech, "bottomTech" => $bottomTech, "curQuery" => $queryStr];

		if(Input::has("aid")){
			$firstLevel = Domains::where("id", Input::get("aid"));
			if($firstLevel->count()){
				$params["firstLevel"] = $firstLevel->get()[0]["cate_name"];
			}
		}

		if(Input::has("cid")){
			$secondLevel = Domains::where("id", Input::get("cid"));
			if($secondLevel->count()){
				$params["secondLevel"] = $secondLevel->get()[0]["cate_name"];
			}
		}

		if(Input::has("tid")){
			$thirdLevel = Techs::where("id", Input::get("tid"));
			if($thirdLevel->count())
			{
				$params["thirdLevel"] = $thirdLevel->get()[0]["cate_name"];
			}
		}

		return view('user.industry.project', $params)->withPresenter($presenter)->withIsProject(true)->withIsIndustry(true);
	}

	public function showDetail()
	{
		$pid = (int)Input::get('pid',0);
		if($pid <= 0){
			return App::abort(404);
		}
		$uid = $this->getUid();
		// 判断是否已收藏
		$isCollect = Collecttion::where("type", 0)->where("relate_id", $pid)->where("uid", $uid)->count();

		// 判断是否为节能公司
		$isSaver = Session::has("user") ? Session::get("user")["role_id"] : 0;

		$model = Projects::with(['province', 'city', 'area', 'investmentType', 'projectDomain', 'projectDomain.domain', 'projectDomain.domain.parent', "user", "projectProgress" => function($query){
			$query->orderBy("progress_time", "asc");
		}, "biddings", "biddings.user", "mainBody", "mainBody.mainBody", "technologies", "technologies.technology", "devices", "devices.device"])->where("verify_state", 1)->where('id', $pid);
		if($model->count()){
			$model = $model->get()[0];
			switch($model["user"]["role_id"]){
				case env("ENERGY"):
					$model->load("user.poweruser");
					$model["userData"] = $model["user"]["poweruser"];
					unset($model["user"]["poweruser"]);
				break;
				case env("SAVER"):
					$model->load("user.energysaver");
					$model["userData"] = $model["user"]["energysaver"];
					unset($model["user"]["energysaver"]);
				break;
				case env("DEVICE_TECH"):
					$model->load("user.devicetech");
					$model["userData"] = $model["user"]["devicetech"];
					unset($model["user"]["devicetech"]);
				break;
				case env("THIRD"):
					$model->load("user.thirdparty");
					$model["userData"] = $model["user"]["thirdparty"];
					unset($model["user"]["thirdparty"]);
				break;
				case env("ASSOCIATION"):
					$model->load("user.association");
					$model["userData"] = $model["user"]["association"];
					unset($model["user"]["association"]);
				break;
				case env("GOVERNMENT"):
					$model->load("user.government");
					$model["userData"] = $model["user"]["government"];
					unset($model["user"]["government"]);
				break;
			}
			if(isset($model["biddings"]))
			{
				$i = 0;
				foreach($model["biddings"] as $bidding)
				{
					switch($bidding["user"]["role_id"]){
						case env("ENERGY"):
							$bidding->load("user.poweruser");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["poweruser"];
							unset($model["biddings"][$i]["user"]["poweruser"]);
							break;
						case env("SAVER"):
							$bidding->load("user.energysaver");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["energysaver"];
							unset($model["biddings"][$i]["user"]["energysaver"]);
							break;
						case env("DEVICE_TECH"):
							$bidding->load("user.devicetech");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["devicetech"];
							unset($model["biddings"][$i]["user"]["devicetech"]);
							break;
						case env("THIRD"):
							$bidding->load("user.thirdparty");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["thirdparty"];
							unset($model["biddings"][$i]["user"]["thirdparty"]);
							break;
						case env("ASSOCIATION"):
							$bidding->load("user.association");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["association"];
							unset($model["biddings"][$i]["user"]["association"]);
							break;
						case env("GOVERNMENT"):
							$bidding->load("user.government");
							$model["biddings"][$i]["userData"] = $model["biddings"][$i]["user"]["government"];
							unset($model["biddings"][$i]["user"]["government"]);
							break;
					}
					$i++;
				}
			}
		}else{
			return App::abort(404);
		}

		return view('user.industry.project_detail', ["model" => $model->toArray(), 'isCollect' => $isCollect, "isSaver" => $isSaver])->withIsIndustry(true);
	}



	public function addDescription()
	{
		$uid = $this->getUid();
		if(!$uid)
		{
			return self::error(self::NOT_LOGIN);
		}
		$pid = Input::get("pid");
		$des = Input::get("des");
		$model = new ProjectBidding;
		$model->project_id = $pid;
		$model->description = $des;
		$model->uid = $uid;
		$model->save();
		return $this->json([]);


	}

	/*
	 * Show the form for creating a new resource.
	 *
	 * @return Response

	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

	public function projectList()
	{
		return view("user.industry_project_list");
	}

}
